﻿var http=require("http");
var path=require('path');
var url=require('url');
var fs=require('fs');
  
http.createServer("request",function(req,res){
   req.url=req.url.toLowerCase();
   req.method=req.method.toLowerCase();
 var publicDir=path.join(__dirname,'lunbo.json');
      if(req.url=='/'){
        fs.readFile(publicDir,function(err,data){
     	if (err) throw err;
     	else{
     	res.setHeader("Content-Type","text/json");
     	res.setHeader("Access-Control-Allow-Origin","*");
     	res.end(data);
     	}
     })
 	
 }else if(req.url=='/news'){
	fs.readFile(path.join(__dirname,'news.json'),"utf-8",function(err,data){
		if (err) throw err;
		else{
		res.setHeader("Content-Type","text/json");
		res.setHeader("Access-Control-Allow-Origin","*");
		res.end(data);
		}
	}) 
 }else if(req.url=='/shop'){
	fs.readFile(path.join(__dirname,'shop.json'),"utf-8",function(err,data){
		if (err) throw err;
		else{
		res.setHeader("Content-Type","text/json");
		res.setHeader("Access-Control-Allow-Origin","*");
		res.end(data);
		}
	}) 
 }else if(req.url=='/car'){
	fs.readFile(path.join(__dirname,'car.json'),"utf-8",function(err,data){
		if (err) throw err;
		else{
		res.setHeader("Content-Type","text/json");
		res.setHeader("Access-Control-Allow-Origin","*");
		res.end(data);
		}
	}) 
 }
 else if(req.url.startsWith('/list/')){
		 var str=req.url.toString()
		 var id=str.substring(str.lastIndexOf("/")+1)
	fs.readFile(path.join(__dirname,'list.json'),function(err,data){
		if (err) throw err;
		else{
		res.setHeader("Content-Type","text/json");
		res.setHeader("Access-Control-Allow-Origin","*");
		var arr=JSON.parse(data).message;
		for (var i = 0; i < arr.length; i++) {
			if(arr[i].id==id){
				var data=arr[i]
				res.end(JSON.stringify(data));	
			}
		}
		
		}
	}) 
}else if(req.url.startsWith('/plun/')){
	var str=req.url.toString()
	var id=str.substring(str.lastIndexOf("/")+1)
fs.readFile(path.join(__dirname,'plun.json'),function(err,data){
 if (err) throw err;
 else{
 res.setHeader("Content-Type","text/json");
 res.setHeader("Access-Control-Allow-Origin","*");
		 res.end(data);	
 }
}) 
}
else{
 	res.end("没有文件404")
 }
}).listen(3030,function () {
	console.log("服务器启动了，请访问http://localhost:3030")
})